package com.mt.component.context;

import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 类名称：EJBContext <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：2012-11-15 下午10:21:11 <br>
 */
public class EJBContext implements BeanContext {
	
	private static BeanContext locator;
	
	private Map<String,Object> beans = new HashMap<String,Object>();
	private InitialContext context;
	
	public static BeanContext getInstance() {
		if(locator == null) {
			try {
				locator = new EJBContext();
			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
		return locator;
	}
	
	private EJBContext() throws NamingException{
		initContext();
	}
	
	private void initContext() throws NamingException {
		if(context == null) {
			context = new InitialContext();
		}
	}

	@Override
	public <T> T getBean(Class<T> clazz) {
		String className = getClassName(clazz);
		if(beans.containsKey(className)) 
			return (T) beans.get(className);
		try {
			beans.put(className, context.lookup(className + "/remote"));
			return (T) beans.get(className);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static <T> String getClassName(Class<T> clazz){
		String allName = clazz.getName();
		return clazz.getName().substring(allName.lastIndexOf(".") + 1);
	}
}
